package com.case5.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.case5.service.LoginService;
import com.case5.util.HttpUtil;
import com.google.gson.Gson;

/**
 * Servlet implementation class Login
 */
@WebServlet("/Login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Login() {
        super();
    }


	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
		//response.getWriter().append("Served at: ").append(request.getContextPath());
	}


	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out = resp.getWriter();
		// 从前端在req中提交的code取出来
				String code = req.getParameter("code");
				String AppId = "wxae30f5069a505c83";
				String AppSecret="9baced9782c2b4c28acc9fa5fc06cca0";
				String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + AppId + "&secret=" + AppSecret + "&js_code=" + code + "&grant_type=authorization_code";
				// 发送请求到微信API，获取用户的openid
				System.out.println(code);
				HttpUtil httpUtil = new HttpUtil();
				Map<String,String> map = new HashMap<>();
				String jsonStr = httpUtil.doGet(url, map);
				map = new Gson().fromJson(jsonStr, Map.class);
				// 生成登入凭证token,这里使用时间戳，实际上应使用更复杂的生成方法
				String token = "token_"+new Date().getTime();
				// 获取用户的openid
				String openId = map.get("openid");
				System.out.println(openId);
				// 将openid 和 token 传递到服务层，做下一步业务处理
				LoginService loginService = new LoginService();
				loginService.login(openId, token);
	}

}
